﻿package {
	import flash.display.*;
	import flash.events.*;
	import flash.utils.Dictionary;
	import flash.events.Event;
	import covert;

	public class FramePlayer extends Bitmap {
		var now = null,seq:int;
		var pos:Number,fps:Number = 1;
		var fcount:Number = 1;
		var frame:Dictionary = new Dictionary();
		var image:Array = [];
		function FramePlayer() {
		}
		function goto(act = null,num:int = -1) {
			fcount--;
			if(fcount > 0)return;
			fcount = fps;
			if (num != -1) {
				now = act;
				pos = frame[act].from+num;
				bitmapData = image[pos];
			} else {
				if (act == now || act == null || act is Event) {
					pos++;
					if (pos > frame[now].to) {
						if (frame[now].call != null) {
							stop();
							frame[now].call();
						}
						if(frame[now].jump == ''){
							stop();
						}else{
							now = frame[now].jump;
							pos = frame[now].from;
							fps = frame[act].fps
						}
					}
				} else {
					pos = frame[act].from;
					now = act;
					fps = frame[act].fps;
				}
				bitmapData = image[pos];
			}
			seq = pos - frame[act].from;
		}
		function addAction(motion,pic,col,row,valid = null) {
			var ef = covert.divide(pic,col,row,valid);
			var num = image.length;
			image = image.concat(ef);
			frame[motion] = new ActionNode(num,num + ef.length - 1,'');
		}
		function addActions(names:Array,fs:Array,pic,col:int,row:int,fps:Number = 1) {
			var point:int = image.length;
			image = image.concat(covert.divide(pic,col,row));
			for (var i = 0; i <names.length; i++) {
				frame[names[i]] = new ActionNode(point, point + fs[i] - 1,names[i]);
				frame[names[i]].fps = fps;
				point += fs[i];
			}
		}
		function setActionNext(motion,arg1,arg2 = 0) {
			if (motion is Array) {
				for(var i:int = 0;i < motion.length;i++){
					actionNext(motion[i],arg1[i],0)
				}
			} else {
				actionNext(motion,arg1,arg2)
			}
		}
		function setActionCallback(motion,call) {
			frame[motion].call = call;
		}
		function setActionTime(motion,time:Number){
			fps = (frame[motion].to - frame[motion].from)/(stage.frameRate * time)
		}
		private function actionNext(motion,arg1,arg2) {
			var action = frame[motion];
			var jump:String;
			if (arg1 is Boolean) {
				jump = arg1 == true ? motion : '';
			} else {
				jump = arg1;
			}
			action.jump = jump;
		}
		function start(){
			addEventListener(Event.ENTER_FRAME,goto);
		}
		function stop(){
			removeEventListener(Event.ENTER_FRAME,goto);
		}
	}
}
class ActionNode {
	var from:int,to:int;
	var jump:String;
	var fps:Number = 1;
	var call:Function;
	function ActionNode(from,to,jump) {
		this.from = from;
		this.to = to;
		this.jump = jump;
	}
}